// Ionic Starter App
var app = angular.module('starter', ['ionic', 'ngStorage', 'ngCordova', 'ngMessages','wxConfig', 'ionic-datepicker','Encryption','ionic-timepicker', 'starter.services', 'home.module', 'donation.module', 'works.module', 'account.module', 'ngSanitize','admin.module'])

  .run(function ($state,$ionicPlatform,$localStorage,$rootScope,$location,$http,storageService,wxOpenIdService,openIdMessageService) {
    $rootScope.version=version;
      $rootScope.openId = storageService.get('openId');
      if($rootScope.openId == null || $rootScope.openId==''){
          var  code = getQueryString('code');
          if(code!=null&&code!=''){
              var openId =  wxOpenIdService.getOpenId(code);
              openId.then(function (result) {
                  //console.log(result);
                  $rootScope.openId=result.data.openId;
                  storageService.set('openId',result.data.openId);
                  storageService.set('accessToken',result.data.accessToken);
                  openIdMessageService.findBlack($rootScope.openId).then(function (res) {
                      if(res.successful){
                          $state.go('blackUser');
                          history.pushState(null, null, document.URL);
                          window.addEventListener('popstate', function () {
                              WeixinJSBridge.call('closeWindow');
                          });
                      }
                  })
              })
          }else {
              wxOpenIdService.getCode();
          }
      }else {
          openIdMessageService.findBlack($rootScope.openId).then(function (res) {
              if(res.successful){
                  $state.go('blackUser');
                  history.pushState(null, null, document.URL);
                  window.addEventListener('popstate', function () {
                      WeixinJSBridge.call('closeWindow');
                  });
              }
          })
      }
    $ionicPlatform.ready(function () {
      //$rootScope.userInfo=JSON.parse($localStorage.userInfo);
      // console.info("$ionicPlatform ready.:"+$localStorage.userInfo);
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        cordova.plugins.Keyboard.disableScroll(true);
      }
      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }
    });
      $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams,current) {
          //禁止路由缓存页面
          if (typeof(current) !== 'undefined'){
              $templateCache.remove(current.templateUrl);
          }
      });
  })
    .config(function (ionicDatePickerProvider) {
        var datePickerObj = {
            inputDate: new Date(),
            setLabel: '确定',
            todayLabel: 'Today',
            closeLabel: '关闭',
            mondayFirst: false,
            weeksList: ["日", "一", "二", "三", "四", "五", "六"],
            monthsList: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],

            templateType: 'popup',
            from: new Date(new Date().setDate(new Date().getDate()+3)),
            showTodayButton: false,
            dateFormat: 'dd MMMM yyyy',
            closeOnSelect: false,
            //disableWeekdays: [6],
        };
        ionicDatePickerProvider.configDatePicker(datePickerObj);
    })
    .config(function (ionicTimePickerProvider) {
        var timePickerObj = {
            inputTime:((new Date()).getHours() * 60 * 60),
            titleLabel:'选择时间',
            format: 24,
            step: 10,
            setLabel: '确定',
            closeLabel: '关闭'
        };
        ionicTimePickerProvider.configTimePicker(timePickerObj);
    })
  .config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

    console.log($ionicConfigProvider)

    $ionicConfigProvider.platform.ios.tabs.style('standard');
    $ionicConfigProvider.platform.ios.tabs.position('bottom');
    $ionicConfigProvider.platform.android.tabs.style('standard');
    $ionicConfigProvider.platform.android.tabs.position('standard');

    $ionicConfigProvider.platform.ios.navBar.alignTitle('center');
    $ionicConfigProvider.platform.android.navBar.alignTitle('center');

    $ionicConfigProvider.platform.ios.backButton.text("返回").previousTitleText(false).icon('ion-ios-arrow-back');
    $ionicConfigProvider.platform.android.backButton.text("返回").previousTitleText(false).icon('ion-ios-arrow-back');

    $ionicConfigProvider.platform.ios.views.transition('ios');
    $ionicConfigProvider.platform.android.views.transition('android');

    $ionicConfigProvider.scrolling.jsScrolling(true);

    $stateProvider
      .state('tabs', {
        url: '/tab',
        abstract: true,
        templateUrl: 'templates/tabs.html'+ '?datestamp=' + (new Date()).getTime(),
          controller: 'tabCtrl'
      })
      .state('tabs.home', {
        url: '/home',
        cache:false,
        views: {
          'tab-home': {
            templateUrl: 'templates/tab-home.html'+ '?datestamp=' + (new Date()).getTime(),
            controller: 'homeCtrl'

          }
        }
      })
      .state('loading', {
        url: '/loading',
        templateUrl: 'templates/loading.html'+ '?datestamp=' + (new Date()).getTime(),
        controller: 'loadingCtrl'
      })
        .state('about', {
            url: '/about',
            templateUrl: 'templates/about.html'+ '?datestamp=' + (new Date()).getTime(),
            // controller: 'loadingCtrl'
        })
        .state('tabs.coin', {
            url: '/coin',
            cache:false,
            views: {
                'tab-home': {
                    templateUrl: 'templates/coin.html'+ '?datestamp=' + (new Date()).getTime(),
                    controller: 'coinCtrl',
                    prefetchTemplate:false
                }
            }
        })
      .state('tabs.coin_bank', {
            url: '/coin_bank/:bankId',
            cache:false,
            views: {
                'tab-home': {
                    templateUrl: 'templates/coin_bank.html'+ '?datestamp=' + (new Date()).getTime(),
                    controller: 'coin_bankCtrl',
                    prefetchTemplate:false
                }
            }
      })
      .state('tabs.coin_bankNet', {
          url: '/coin_bankNet/:bankId',
          views: {
              'tab-home': {
                  templateUrl: 'templates/coin_bankNet.html'+ '?datestamp=' + (new Date()).getTime(),
                  controller: 'coin_bankNetCtrl',
                  prefetchTemplate:false
              }
          }
      })
        .state('tabs.coin_zibi', {
            url: '/coin_zibi/:bankId',
            views: {
                'tab-home': {
                    templateUrl: 'templates/coin_zibi.html'+ '?datestamp=' + (new Date()).getTime(),
                    controller: 'coin_bankNetCtrl',
                    prefetchTemplate:false
                }
            }
        })
        .state('tabs.coin_list', {
            url: '/coin_list',
            views: {
                'tab-home': {
                    templateUrl: 'templates/coin_list.html'+ '?datestamp=' + (new Date()).getTime(),
                    controller: 'coin_listCtrl',
                    prefetchTemplate:false
                }
            }
        })

      .state('tabs.account', {
          url: '/account',
          views: {
              'tab-account': {
                  templateUrl: 'templates/tab-account.html'+ '?datestamp=' + (new Date()).getTime(),
                  controller: 'accountCtrl',
                  prefetchTemplate:false
              }
          }
      })
      .state('tabs.getUser', {
          url: '/getUser',
          cache:false,
          views: {
              'tab-account': {
                  templateUrl: 'templates/tab-getUser.html'+ '?datestamp=' + (new Date()).getTime(),
                  controller: 'getUserCtrl',
                  prefetchTemplate:false
              }
          }
      })
        .state('tabs.complain',{
            url:'/complain',
            cache:false,
            views:{
                'tab-account':{
                    templateUrl:'templates/complain.html'+'?datestamp=' + (new Date()).getTime(),
                    controller:'complainCtrl',
                    prefetchTemplate:false
                }
            }
        })
        .state('tabs.viewUser', {
            url: '/viewUser',
            views: {
                'tab-account': {
                    templateUrl: 'templates/viewUser.html'+ '?datestamp=' + (new Date()).getTime(),
                    controller: 'viewUserCtrl',
                    prefetchTemplate:false
                }
            }
        })
        .state('tabs.history',{
            url:'/history',
            cache:false,
            views:{
                'tab-history':{
                    templateUrl:'templates/history.html'+ '?datestamp=' + (new Date()).getTime(),
                    controller:'historyCtrl',
                    prefetchTemplate:false
                }
            }
        })
        .state('tabs.instr',{
            url:'/instr',
            cache:false,
            views:{
                'tab-history':{
                    templateUrl:'templates/instructions.html'+ '?datestamp=' + (new Date()).getTime(),
                    //controller:'historyCtrl',
                    prefetchTemplate:false
                }
            }
        })
        .state('admin',{
        url:'/admin',
        abstract:true,
        templateUrl:'admin/tabs.html'+ '?datestamp=' + (new Date()).getTime(),
          prefetchTemplate:false
    })
        .state('login', {
            url: '/login',
            templateUrl: 'admin/login.html'+ '?datestamp=' + (new Date()).getTime(),
            prefetchTemplate:false
        })
        .state('admin.home',{
            url:'/home',
            views: {
                'admin-home': {
                    templateUrl: 'admin/tab-home.html'+ '?datestamp=' + (new Date()).getTime(),
                    controller: 'adminHomeCtrl',
                    prefetchTemplate:false
                }
            }
        })
        .state('admin.work',{
            url:'/work',
            views: {
                'admin-work': {
                    templateUrl: 'admin/tab-work.html'+ '?datestamp=' + (new Date()).getTime(),
                    controller: 'adminWorkCtrl',
                    prefetchTemplate:false
                }
            }
        })
        .state('details',{
            url:'/details',
            cache:false,
            templateUrl:'admin/details.html'+ '?datestamp=' + (new Date()).getTime(),
            controller:'adminDetailsCtrl',

        })
        .state('blackUser',{
          url:'/blackUser',
          cache:false,
          templateUrl:'templates/blackUser.html'+ '?datestamp=' + (new Date()).getTime(),
      })

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/tab/home');

  })
    .config(function($urlRouterProvider){
        var state =getQueryString('state');
        if(state!=null && state!=''){
            $urlRouterProvider.otherwise(state);
        }
    })

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
